package com.skymobi.cassandra.utils;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.utils.FileUtils;

public class CassandraServiceDataCleaner {
	public void prepare() throws IOException {
		makeDirsIfNotExist();
		cleanupDataDirectories();
	}

	/**
	 * Deletes all data from cassandra data directories, including the commit
	 * log.
	 * 
	 * @throws IOException
	 *             in case of permissions error etc.
	 */
	public void cleanupDataDirectories() throws IOException {
		for (String s : getDataDirs()) {
			cleanDir(s);
		}
	}

	public void makeDirsIfNotExist() throws IOException {
		for (String s : getDataDirs()) {
			mkdir(s);
		}
	}

	private Set<String> getDataDirs() {
		Set<String> dirs = new HashSet<String>();
		for (String s : DatabaseDescriptor.getAllDataFileLocations()) {
			dirs.add(s);
		}
		dirs.add(DatabaseDescriptor.getLogFileLocation());
		return dirs;
	}

	private void mkdir(String dir) throws IOException {
		FileUtils.createDirectory(dir);
	}

	private void cleanDir(String dir) throws IOException {
		File dirFile = new File(dir);
		if (dirFile.isDirectory() && dirFile.exists()) {
			FileUtils.delete(dirFile.listFiles());
		}
	}
}
